package com.changgou.util;

import com.changgou.file.FastDFSFile;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.core.io.ClassPathResource;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

public class FastDFSClient {

    /**
     * 初始化tracker信息
     */
    static {
        try {
            //获取tracker的配置文件fdfs_client.conf的位置
            String filePath = new ClassPathResource("fdfs_client.conf").getPath();
            //加载tracker配置信息
            ClientGlobal.init(filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取TrackerServer
     * @return
     */
    public static TrackerServer getTrackerServer() {
        TrackerServer trackerServer = null;
        try {
            trackerServer =  new TrackerClient().getConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return trackerServer;
    }

    /**
     * 获取StorageClient
     * @return
     */
    public static StorageClient getStorageClient() {
        return new StorageClient(getTrackerServer(), null);
    }

    /**
     * 文件上传
     * @param file : FastDFSFile上传的文件封装对象
     * @return
     */
    public static String[] upload(FastDFSFile file) {

        String[] uploadResults = null;

        try {
            //附加数据
            NameValuePair[] meta_list = new NameValuePair[1];
            meta_list[0] = new NameValuePair("author", file.getauthor());
            /*//创建一个TrackerClient对象
            TrackerClient trackerClient = new TrackerClient();
            //通过TrackerClient对象获取TrackerServer
            TrackerServer trackerServer = trackerClient.getConnection();
            //通过TrackerServer来获取StorageClient对象
            StorageClient storageClient = new StorageClient(trackerServer, null);*/
            //获取StorageClient
            StorageClient storageClient = getStorageClient();
            /**
             * 通过StorageClient操作Storage[文件上传],并获取返回的文件上传信息
             * 1:要上传的文件的字节数组
             * 2:文件的扩展名
             * 3:附加价值对数据
             *
             * 返回数据：
             *      1:当前文件所存储的Storage的组  例如:group1
             *      2:文件存储的路径  例如: M00/02/44/2345678.jpg
             */
            uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return uploadResults;
    }

    /**
     * 获取文件信息
     * @param groupName:组名
     * @param remoteFileName：文件存储完整名
     */
    public static FileInfo getFile(String groupName, String remoteFileName) {

        FileInfo fileInfo = null;

        try {
            /*TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer = trackerClient.getConnection();
            StorageClient storageClient = new StorageClient(trackerServer, null);*/
            //获取文件信息
            fileInfo = getStorageClient().get_file_info(groupName, remoteFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileInfo;
    }

    /**
     * 文件下载
     * @param groupName:组名
     * @param remoteFileName:文件存储的名字
     * @return InputStream
     */
    public static InputStream downLoadFile(String groupName, String remoteFileName) {
        ByteArrayInputStream byteArrayInputStream = null;
        try {
            StorageClient storageClient = getStorageClient();
            byte[] bytes = storageClient.download_file(groupName, remoteFileName);
            byteArrayInputStream = new ByteArrayInputStream(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return byteArrayInputStream;
    }

    /**
     * 删除文件
     * @param groupName:组名
     * @param remoteFileName:文件存储的名字
     */
    public static void deleteFile(String groupName, String remoteFileName) {
        try {
            getStorageClient().delete_file(groupName, remoteFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取Storage信息
     * @param groupName ：Storage的组名
     */
    public static StorageServer getStorage(String groupName) {

        StorageServer storageServer = null;

        try {
            //创建一个TrackClient
            TrackerClient trackerClient = new TrackerClient();
            //创建TrackerServer
            TrackerServer trackerServer = trackerClient.getConnection();
            //获取StorageServer
            storageServer = trackerClient.getStoreStorage(trackerServer, groupName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return storageServer;
    }

    /**
     * 获取Storage的IP和端口信息
     * @param groupName ：Storage的组名
     * @param remoteFileName : 路径名
     */
    public static ServerInfo[] getServerInfo(String groupName, String remoteFileName) {
        ServerInfo[] serverInfos = null;
        try {
            //创建一个TrackClient
            TrackerClient trackerClient = new TrackerClient();
            //创建TrackerServer
            TrackerServer trackerServer = trackerClient.getConnection();
            //获取ServerInfo[]
            serverInfos = trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return serverInfos;
    }

    /**
     * TrackerServer的Http请求地址   http://192.168.211.132:8080
     */
    public static String getTrackerUrl() {
        TrackerServer trackerServer = getTrackerServer();
        return "http://"+trackerServer.getInetSocketAddress().getHostString() + ":" + ClientGlobal.getG_tracker_http_port();
    }

    public static void main(String[] args) throws Exception {

        /*FileInfo fileInfo = getFile("group1", "M00/00/00/wKjThF08CNGAV5OmAAAAReng5zw730.txt");
        System.out.println(fileInfo.getSourceIpAddr());
        System.out.println(fileInfo.getFileSize());
        System.out.println(fileInfo.getCrc32());*/

        /*FileOutputStream os = new FileOutputStream("C:/javaee64/1.jpg");
        InputStream is = downLoadFile("group1", "M00/00/00/wKjThF04F9SAJj7IAAoAAFSKsG8372.jpg");
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }
        is.close();
        os.close();*/

        //deleteFile("group1", "M00/00/00/wKjThF08CNGAV5OmAAAAReng5zw730.txt");

        /*System.out.println(getStorage("group1").getStorePathIndex());
        System.out.println(getStorage("group1").getInetSocketAddress().getHostString());
        System.out.println(getStorage("group1").getInetSocketAddress().getPort());*/

        /*ServerInfo[] serverInfos = getServerInfo("group1", "M00/00/00/wKjThF04F9SAJj7IAAoAAFSKsG8372.jpg");
        for (ServerInfo serverInfo : serverInfos) {
            System.out.println(serverInfo.getPort());
            System.out.println(serverInfo.getIpAddr());
        }*/

        System.out.println(getTrackerUrl());
    }
}
